<?php
namespace app\common\controller;

use app\common\model\Menus;
use app\common\service\BaseService;
use app\common\service\LayuiListApiService;
use app\common\service\SysConfigService;
use app\common\service\UserService;
use app\common\util\ReturnMsgUtil;
use think\Controller;
use think\db\Query;
use think\Exception;
use think\facade\Config;
use think\Model;
use think\Request;
use think\Validate;

/**
 * Created by PhpStorm OF yuyi.
 * User: YUYI
 * Date: 2018/5/9 0009
 * Time: 上午 9:20
 * Administrator
 */

class Base extends Controller
{
    /**
     * @var string $getList  需要用到的模型名
     */
    protected $getList = '';
    /**
     * @var string|array $getListWith 需要关联的模型名
     */
    protected $getListWith = '';

    protected $isPublic = false;
    /**
     * @var Model
     */
    protected $model;

    use ReturnMsgUtil;
    public function __construct(Request $request = null)
    {
        parent::__construct();
        $user = UserService::getCurrentUserInfo();
        $this->assign('user',$user);
        if (!$this->isPublic($request)){
            if (!$user){
                if ($request->isAjax()){
                    exit($this->errorInfo('未登录，无法执行此操作'));
                }
                $this->error('非法访问','/index/auth/index');
            }
        }
        $this->setModel();
        $menus = Menus::all(['type'=>2,'flag'=>99]);
        $this->assign('menus',$menus);
        $form = Config::get()['form_url'];
        $this->assign('_form',$form);
        $sysConfigs = SysConfigService::getAppBaseConfigs();
        $host = SysConfigService::getURLConfig('A_HOST');
        $this->assign('sysConfigs',$sysConfigs);
        $this->assign('host',$host);
    }

    /**
     * 初始化model
     */
    private function setModel()
    {
        $this->model = $this->{'model'.$this->getList};
    }

    /**
     * 是否是无需登录即可访问路径
     * @param Request $request
     * @return bool
     */
    public function isPublic(Request $request)
    {
        if ($this->isPublic === true){
            return $this->isPublic;
        }else{
            if (is_array($this->isPublic)){
                foreach ($this->isPublic as $item){
                    if ($request->action() == strtolower($item)){
                        return true;
                    }
                }
            }elseif (is_string($this->isPublic) && $this->isPublic == $request->action()){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取列表通用方法
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        $where = [];
        $model = 'model'.$this->getList;
        foreach (input() as $k => $w ){
            if (($k=='page' ||$k=='limit')){
                continue;
            }
            if ($w) $where[$this->model->getTable().'.'.$k] = $w;
        }
        $qcms = ($this->model)::all(function (Query $query) use ($where){
            $query->where($where)->page(input('page')?:1)->limit(input('limit')?:10);
        },$this->getListWith ? : null);
        $data = LayuiListApiService::getData(($this->$model)->count(),$qcms);
        return $data;
    }

    /**
     * 删除数据通用方法
     * @param $id int 数据ID
     * @return string
     * @throws \think\exception\DbException
     */
    public function del($id)
    {
        if (!$id){
            return $this->errorInfo('非法访问');
        }
        $menu = ($this->model)::get($id);
        if (!$menu){
            return $this->errorInfo('异常访问');
        }
        $r = $menu->delete();
        if ($r===false){
            return $this->errorInfo('删除失败');
        }
        return $this->successInfo('删除成功');
    }


    /**
     * @param $name
     * @return Model|BaseService
     * @throws Exception
     */
    public function __get($name)
    {
        // TODO: Implement __get() method.
        if (isStringInString($name,'model')){
            $structure = 'model';
        }
        if (isStringInString($name,'service')){
            $structure = 'service';
        }
        $modelClassName = getCurrentModular(get_called_class()).'\\'.$structure.'\\'.substr($name,strlen($structure));
        if (class_exists($modelClassName)) {
            return new $modelClassName();
        }else{
            $modelClassName = getCommonModular().'\\'.$structure.'\\'.substr($name,strlen($structure));
            if (class_exists($modelClassName)){
                return  new $modelClassName();
            }
            throw new Exception('The class is not exist:'.$modelClassName);
        }
    }
}